package com.example.libraryManager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.libraryManager.entity.Books;
import com.example.libraryManager.entity.Borrow;
import com.example.libraryManager.mapper.BooksMapper;
import com.example.libraryManager.mapper.BorrowMapper;
import com.example.libraryManager.service.IBorrowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.libraryManager.utils.ResultUtils;
import com.example.libraryManager.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author admin
 * @since 2022-09-02
 */
@Service
public class BorrowService extends ServiceImpl<BorrowMapper, Borrow> implements IBorrowService {

    @Autowired
    BorrowMapper borrowMapper;

    @Autowired
    BooksMapper booksMapper;

    /**
     * 收藏 书籍
     * @param borrow
     * @return
     */
    @Override
    public ResultVo saveAndCheck(Borrow borrow) {
        QueryWrapper<Borrow> wrapper=new QueryWrapper<>();
        wrapper.eq("u_id",borrow.getUId()).eq("book_id",borrow.getBookId());

        Borrow one = borrowMapper.selectOne(wrapper);

        if (one==null){
            borrowMapper.insert(borrow);
            return ResultUtils.success(null);
        }else{
            return ResultUtils.failed(2);
        }
    }

    /**
     * 收藏 分页查询
     * @param user
     * @return
     */
    @Override
    public ResultVo pageList(Integer user) {

        QueryWrapper<Borrow> wrapper=new QueryWrapper<>();
        wrapper.eq("u_id",user);

        List<Borrow> records = borrowMapper.selectList(wrapper);
        List<Books> booksList=new ArrayList<>();

        for (Borrow record : records) {
            QueryWrapper<Books> booksQueryWrapper=new QueryWrapper<>();
            booksQueryWrapper.eq("book_id",record.getBookId());

            Books books = booksMapper.selectOne(booksQueryWrapper);
            if (books!=null){
                booksList.add(books);
            }
        }

        return ResultUtils.success(booksList);
    }

    /**
     * 收藏 删除
     * @param books
     * @return
     */
    @Override
    public ResultVo deleteByBookId(Books books) {
        QueryWrapper<Borrow> wrapper=new QueryWrapper<>();
        wrapper.eq("book_id",books.getBookId());

        int delete = borrowMapper.delete(wrapper);
        if (delete==0){
            return ResultUtils.failed(1);
        }
        return ResultUtils.success(null);
    }
}
